package cn.bjxy.shishaolong.ra_room.controller;

import cn.bjxy.shishaolong.common.ResultMsg;
import cn.bjxy.shishaolong.common.StatusCode;
import cn.bjxy.shishaolong.common.SysConst;
import cn.bjxy.shishaolong.ra_room.entity.RaroomStudentRalation;
import cn.bjxy.shishaolong.ra_room.service.IRaroomStudentRalationService;
import cn.bjxy.shishaolong.system.annotation.Permission;
import cn.bjxy.shishaolong.system.exception.OperatorFailureException;
import cn.bjxy.shishaolong.system.user.entity.SysUserInfo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 答疑室学生相关控制器
 *
 * @Author 时少龙
 * @Date 2019-04-20 14:02
 * @Version 1.0
 */
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/api/web/raroom/student")
public class RaRoomStudentController extends RaroomBaseController {

    @Autowired
    private IRaroomStudentRalationService studentRalationService;

    /**
     * 查询答疑室文件  RoomId 为必填字段
     *
     * @return
     */
    @Permission
    @RequestMapping("/queryByCondition")
    public ResultMsg queryByCondition(HttpServletRequest request, @RequestBody JSONObject param) {
        try {
            //查询条件
            if (!param.containsKey(SysConst.QUERY_CONDITION_KEY)) {
                return retParamFailure();
            }
            SysUserInfo student = param.getObject(SysConst.QUERY_CONDITION_KEY, SysUserInfo.class);
            if (student.getRoomId() == null) return retParamFailure();

            //如果不是老师本人，只显示已通过审核的学生
            Integer currentUserId = getCurrentUserId(request);
            if (!isRoomTeacher(currentUserId, student.getRoomId()))
                student.setStatus(SysConst.RA_ROOM_STUDENT_STATUS_OK);

            //分页查询
            if (param.containsKey(SysConst.PAGA_CURRENT_KEY) && param.containsKey(SysConst.PAGA_SIZE_KEY)) {
                IPage<SysUserInfo> page = new Page<>();
                page.setCurrent(param.getLong(SysConst.PAGA_CURRENT_KEY)).setSize(param.getLong(SysConst.PAGA_SIZE_KEY));
                IPage<SysUserInfo> list = raroomService.queryStudentByCondition(page, student);
                return ResultMsg.success(list);
            } else {  //普通查询
                List<SysUserInfo> list = raroomService.queryStudentByCondition(student);
                return ResultMsg.success(list);
            }
        } catch (OperatorFailureException ofe) {
            ofe.printStackTrace();
            return retOperatorFalueException(ofe);
        } catch (Exception e) {
            e.printStackTrace();
            return retQueryFailure();
        }
    }

    /**
     * 审核学生
     *
     * @return
     */
    @RequestMapping("/verify")
    @Permission
    public ResultMsg verify(HttpServletRequest request, @RequestBody RaroomStudentRalation studentRalation) {
        try {
            if (studentRalation == null) {
                retParamFailure();
            }
            Integer currentUserId = getCurrentUserId(request);
            //如果答疑室未开通，不允许操作
            if (!isRoomOpen(currentUserId)) return retRoomStatusNotOpen();
            studentRalation.setRoomId(getRoomIdByTeacherId(currentUserId));
            raroomService.verify(studentRalation);
            return retSuccess();
        } catch (OperatorFailureException ofe) {
            ofe.printStackTrace();
            return retOperatorFalueException(ofe);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.OPERATOR_FAILURE, StatusCode.OPERATOR_FAILURE_MSG);
        }
    }

    /**
     * 学生申请加入
     *
     * @return
     */
    @RequestMapping("/apply")
    @Permission
    public ResultMsg apply(HttpServletRequest request, @RequestBody JSONObject param) {
        try {
            if (param == null || !param.containsKey(SysConst.ID) || param.getInteger(SysConst.ID) == null) {
                return retParamFailure();
            }
            Integer roomId = param.getInteger(SysConst.ID);
            Integer currentUserId = getCurrentUserId(request);
            //如果答疑室未开通，不允许操作
            if (!roomIsOpen(roomId)) return retRoomStatusNotOpen();
            studentRalationService.save(new RaroomStudentRalation()
                    .setStatus(SysConst.RA_ROOM_STUDENT_STATUS_NOTHANDLE).setRoomId(roomId).setStudentId(currentUserId));
            return retSuccess();
        } catch (OperatorFailureException ofe) {
            ofe.printStackTrace();
            return retOperatorFalueException(ofe);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.OPERATOR_FAILURE, StatusCode.OPERATOR_FAILURE_MSG);
        }
    }

    /**
     * 学生退出答疑室
     *
     * @param param
     * @return
     */
    @DeleteMapping("/quitRoom")
    @Permission
    public ResultMsg quitRoom(HttpServletRequest httRequest, @RequestBody JSONObject param) {
        try {
            if (param == null || !param.containsKey(SysConst.ID) || param.getInteger(SysConst.ID) == null) {
                return retParamFailure();
            }
            Integer roomId = param.getInteger(SysConst.ID);
            Integer studentId = getCurrentUserId(httRequest);
            // 删除
            RaroomStudentRalation studentRalation = new RaroomStudentRalation()
                    .setRoomId(roomId).setStudentId(studentId);
            raroomService.remove(studentRalation);
            return ResultMsg.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.DELETE_FAILUER, StatusCode.DELETE_FAILUER_MSG);
        }
    }

    /**
     * 删除 学生
     *
     * @param param
     * @return
     */
    @DeleteMapping("/delete")
    @Permission
    public ResultMsg delete(HttpServletRequest httRequest, @RequestBody JSONObject param) {
        try {
            if (param == null || !param.containsKey(SysConst.ID) || param.getInteger(SysConst.ID) == null) {
                return retParamFailure();
            }
            Integer id = param.getInteger(SysConst.ID);
            Integer userId = getCurrentUserId(httRequest);
            if (!isRoomOpen(userId)) retRoomStatusNotOpen();
            // 删除
            RaroomStudentRalation studentRalation = new RaroomStudentRalation()
                    .setRoomId(getRoomIdByTeacherId(userId)).setStudentId(id);
            raroomService.remove(studentRalation);
            return ResultMsg.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.DELETE_FAILUER, StatusCode.DELETE_FAILUER_MSG);
        }
    }
}
